/**
 * 巧巧点餐后台管理系统 JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // 侧边栏切换
    const toggleSidebar = document.getElementById('toggleSidebar');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (toggleSidebar) {
        toggleSidebar.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        });
    }
    
    // 移动端自动收起侧边栏
    function checkWindowSize() {
        if (window.innerWidth < 992) {
            sidebar?.classList.add('collapsed');
            mainContent?.classList.add('expanded');
        } else {
            sidebar?.classList.remove('collapsed');
            mainContent?.classList.remove('expanded');
        }
    }
    
    // 初始检查窗口大小
    checkWindowSize();
    
    // 监听窗口大小变化
    window.addEventListener('resize', checkWindowSize);
    
    // 用户下拉菜单
    const userDropdown = document.getElementById('userDropdown');
    if (userDropdown) {
        userDropdown.addEventListener('click', function(e) {
            e.preventDefault();
            const dropdownMenu = this.nextElementSibling;
            dropdownMenu.classList.toggle('show');
            
            // 点击其他区域关闭下拉菜单
            document.addEventListener('click', function closeDropdown(event) {
                if (!userDropdown.contains(event.target)) {
                    dropdownMenu.classList.remove('show');
                    document.removeEventListener('click', closeDropdown);
                }
            });
        });
    }
    
    // 消息自动关闭
    const alerts = document.querySelectorAll('.alert');
    if (alerts.length > 0) {
        alerts.forEach(function(alert) {
            setTimeout(function() {
                // 创建淡出效果
                alert.style.opacity = '1';
                (function fadeOut() {
                    if ((alert.style.opacity -= 0.1) < 0) {
                        alert.style.display = 'none';
                    } else {
                        setTimeout(fadeOut, 50);
                    }
                })();
            }, 5000); // 5秒后开始淡出
        });
    }
    
    // 确认删除
    const deleteBtns = document.querySelectorAll('.delete-btn');
    if (deleteBtns.length > 0) {
        deleteBtns.forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                if (!confirm('确定要删除此项吗？此操作不可恢复！')) {
                    e.preventDefault();
                }
            });
        });
    }
    
    // 图片预览
    const imageInputs = document.querySelectorAll('input[type="file"][accept*="image"]');
    if (imageInputs.length > 0) {
        imageInputs.forEach(function(input) {
            input.addEventListener('change', function() {
                const preview = document.querySelector('#' + input.id.replace('_file', '-preview'));
                if (preview && this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        preview.src = e.target.result;
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });
    }
    
    // 表格行选择
    const tableCheckboxes = document.querySelectorAll('.table .select-checkbox');
    const selectAllCheckbox = document.querySelector('.select-all-checkbox');
    
    if (tableCheckboxes.length > 0 && selectAllCheckbox) {
        // 全选/取消全选
        selectAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            tableCheckboxes.forEach(function(checkbox) {
                checkbox.checked = isChecked;
                const row = checkbox.closest('tr');
                if (row) {
                    if (isChecked) {
                        row.classList.add('selected');
                    } else {
                        row.classList.remove('selected');
                    }
                }
            });
        });
        
        // 单个选择
        tableCheckboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                const row = this.closest('tr');
                if (row) {
                    if (this.checked) {
                        row.classList.add('selected');
                    } else {
                        row.classList.remove('selected');
                        selectAllCheckbox.checked = false;
                    }
                }
                
                // 检查是否全部选中
                const allChecked = Array.from(tableCheckboxes).every(function(cb) {
                    return cb.checked;
                });
                
                if (allChecked) {
                    selectAllCheckbox.checked = true;
                }
            });
        });
    }
    
    // 批量操作按钮
    const batchActionBtns = document.querySelectorAll('.batch-action-btn');
    if (batchActionBtns.length > 0) {
        batchActionBtns.forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                const selectedIds = [];
                tableCheckboxes.forEach(function(checkbox) {
                    if (checkbox.checked) {
                        selectedIds.push(checkbox.value);
                    }
                });
                
                if (selectedIds.length === 0) {
                    e.preventDefault();
                    alert('请先选择要操作的项目');
                } else {
                    const form = this.closest('form');
                    if (form) {
                        const idInput = document.createElement('input');
                        idInput.type = 'hidden';
                        idInput.name = 'ids';
                        idInput.value = selectedIds.join(',');
                        form.appendChild(idInput);
                    }
                    
                    if (this.dataset.action === 'delete' && !confirm(`确定要删除选中的 ${selectedIds.length} 项吗？此操作不可恢复！`)) {
                        e.preventDefault();
                    }
                }
            });
        });
    }
    
    // 表单验证增强
    const forms = document.querySelectorAll('form[data-validate="true"]');
    if (forms.length > 0) {
        forms.forEach(function(form) {
            form.addEventListener('submit', function(e) {
                const requiredFields = form.querySelectorAll('[required]');
                let isValid = true;
                
                requiredFields.forEach(function(field) {
                    if (field.value.trim() === '') {
                        isValid = false;
                        field.classList.add('is-invalid');
                        
                        // 创建或更新错误提示
                        let feedback = field.nextElementSibling;
                        if (!feedback || !feedback.classList.contains('invalid-feedback')) {
                            feedback = document.createElement('div');
                            feedback.className = 'invalid-feedback';
                            field.parentNode.insertBefore(feedback, field.nextSibling);
                        }
                        feedback.textContent = '此字段不能为空';
                    } else {
                        field.classList.remove('is-invalid');
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    // 滚动到第一个错误字段
                    const firstInvalid = form.querySelector('.is-invalid');
                    if (firstInvalid) {
                        firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        firstInvalid.focus();
                    }
                }
            });
            
            // 输入时移除错误状态
            const inputs = form.querySelectorAll('input, select, textarea');
            inputs.forEach(function(input) {
                input.addEventListener('input', function() {
                    this.classList.remove('is-invalid');
                });
            });
        });
    }
}); 